#!/usr/bin/perl
use strict;

sub trim($)
{
	my $string = shift;
	$string =~ s/^\s+//;
	$string =~ s/\s+$//;
	return $string;
}

my $packName=$ARGV[0];
$packName=~s/:/%3A/g;
print $packName,"\n";

my $url='http://search.cpan.org/search?format=xml&query='. $packName;
print $url,"\n";

my $url2=`wget -q "$url" -O -`;

if ($url2 =~ s/<link>(.*?)<\/link>/$1/) {
	my $url2=trim $1;
	print $url2,"\n";
	my $content=`wget -q "$url2" -O -`;

	if ($content =~ /Download:.*? <a href="(.*?)">/) {
		print $1,"\n";
		my $url3="http://search.cpan.org$1";
		print `wget -q "$url3"`;
		my $arch=`basename $1`;
		print `tar xvzf $arch`;
		if ( $arch =~ /(.*?).tar.gz/) {
			my $cur=`pwd`;
			chdir $1;
			print `perl ./Makefile.PL`;
			print `make test && sudo make install`;
			print "going to $cur";
			chdir("..");
		        print `pwd`;
			print `/bin/rm -Rf $1*` if ($ARGV[1] eq "-c") ;	
		}
	}
}

